import { Button, Form, Input } from 'antd'
import cs from 'classnames'
import { useEffect, useState } from 'react'

import { OtpCreate } from '@/api/modules/entity'
import locale from '@/pages/entity/locale'
import styles from '@/pages/entity/style/index.module.less'
import useLocale from '@/utils/useLocale'

type FieldType = {
  username?: string
}

export default function Account({
  email,
  onNext,
}: {
  email: string
  onNext: (_email: string, _mobile: string, _code: string) => void
}) {
  const t = useLocale(locale)
  const [form] = Form.useForm()
  const onContinue = async () => {
    try {
      const values = await form.validateFields()
      console.log('Success:', values)

      sendSms(values.username.toLowerCase())
    } catch (errorInfo) {
      console.log('Failed:', errorInfo)
    }
  }

  const [loading, setLoading] = useState<boolean>(false)

  const sendSms = (email: string) => {
    setLoading(true)
    OtpCreate({ email: email.trim() })
      .then((res) => {
        const { mobile, code } = res.data
        setLoading(false)
        onNext(email, mobile, code)
      })
      .catch(() => {
        setLoading(false)
      })
  }

  useEffect(() => {
    form.setFieldsValue({
      username: email,
    })
  }, [email])

  // const handleInputChange = (event: FormEvent<HTMLInputElement>) => {
  //   const { value } = event.currentTarget as HTMLInputElement
  //   event.currentTarget.value = value.trim()
  // }

  return (
    <>
      <div className={cs('text-[50px] font-bold Roboto text-[#16202D]  pb-[40px]')}>
        {t['form.title']}
      </div>
      <Form autoComplete="off" className={styles['form']} form={form}>
        <Form.Item<FieldType>
          name="username"
          className={cs(styles['form-item'])}
          validateTrigger={['onBlur']}
          rules={[
            { required: true, message: t['form.email.message'] },
            ({}) => ({
              validator(_, value) {
                if (!value) {
                  return Promise.resolve()
                }
                if (
                  /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(
                    value
                  )
                ) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error(t['form.email.error']))
              },
            }),
          ]}
        >
          <Input
            className="ltr-ipt"
            onPressEnter={onContinue}
            allowClear
            placeholder={t['form.email.placeholder']}
            // onInput={handleInputChange}
          />
        </Form.Item>
        <Form.Item className={cs('flex justify-center')}>
          <Button
            loading={loading}
            type="primary"
            onClick={onContinue}
            className={cs(styles['button'])}
          >
            {t['form.continue']}
          </Button>
        </Form.Item>
      </Form>
    </>
  )
}
